package com.cactus.service;

import com.cactus.entity.JeeUserDetails;
import com.cactus.entity.User;
import com.cactus.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * @Author: cactus
 * @CreateDate: 2023/9/14 12:00
 * @Description: 用户
 */
@Service
@Slf4j
public class UserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 区分时后台人员还是我们的用户登录
        String userType = requestAttributes.getRequest().getParameter("userType");
        User user = userMapper.findByUsername(username, userType);
        if (user == null) {
            throw new BadCredentialsException("用户不存在");
        }
        if (user.getStatus() != 1) {
            throw new BadCredentialsException(username + " 您的账号已锁定！");
        }
        if (!new Date().before(user.getEndTime())) {
            throw new BadCredentialsException(username + " 您的账号已过期！");
        }
        return new JeeUserDetails(user);

    }
}
